# -*- coding: utf-8 -*-
"""
HaaS506 RTU ADC模块
提供ADC采集和电源监控功能
"""

from driver import GPIO
import utime

# ADC实例 (使用GPIO模拟)
_di1 = None
_di2 = None
_adc_data = {}
_last_read_time = 0

# 电源监控引脚
_power_pin = None
_power_status = True

def init():
    """初始化ADC模块"""
    global _di1, _di2, _power_pin
    
    try:
        # 不再初始化DI1和DI2，避免与GPIO模块冲突
        # DI1和DI2由GPIO模块管理，ADC模块通过GPIO模块读取
        _di1 = None
        _di2 = None
        
        # 初始化电源监控引脚（如果存在）
        try:
            _power_pin = GPIO()
            _power_pin.open("POWER_DETECT")
            print("[ADC] Power detection pin initialized")
        except:
            print("[ADC] Power detection pin not available")
            _power_pin = None
        
        print("[ADC] ADC module initialized (using GPIO module for DI1/DI2)")
        return True
        
    except Exception as e:
        print("[ADC] Init error: {}".format(e))
        return False

def read_adc():
    """读取ADC值"""
    global _adc_data, _last_read_time
    
    try:
        _last_read_time = utime.time()
        
        # 从GPIO模块读取数字输入值，避免重复打开引脚
        try:
            import rtu_gpio
            di_status = rtu_gpio.read_digital_inputs()
            
            if di_status:
                di1_value = di_status.get("di1", 0)
                di2_value = di_status.get("di2", 0)
            else:
                # 如果GPIO模块返回None，使用默认值
                di1_value = 1  # 默认有电
                di2_value = 0
        except Exception as gpio_e:
            print("[ADC] Failed to read from GPIO module: {}, using defaults".format(gpio_e))
            di1_value = 1  # 默认有电
            di2_value = 0
        
        # 模拟ADC数据（使用数字输入）
        _adc_data = {
            "di1": di1_value,
            "di2": di2_value,
            "timestamp": _last_read_time
        }
        
        return _adc_data
        
    except Exception as e:
        print("[ADC] Read ADC error: {}".format(e))
        return None

def read_power_status():
    """读取电源状态"""
    global _power_status
    
    if not _power_pin:
        return True  # 如果没有电源检测引脚，默认有电
    
    try:
        # 读取电源状态（假设高电平表示有电）
        _power_status = bool(_power_pin.read())
        return _power_status
        
    except Exception as e:
        print("[ADC] Read power status error: {}".format(e))
        return True

def get_power_voltage():
    """获取电源电压"""
    # 由于使用GPIO模拟，返回固定值
    return 24.0  # 假设24V供电

def check_power_warning():
    """检查电源告警"""
    try:
        # 简化版本，直接检查电源状态
        power_status = read_power_status()
        
        if not power_status:
            print("[ADC] Power off detected!")
            return True
        
        return False
        
    except Exception as e:
        print("[ADC] Power warning check error: {}".format(e))
        return False

def check_current_warning():
    """检查电流告警"""
    try:
        # 简化版本，暂不实现电流检测
        return False
        
    except Exception as e:
        print("[ADC] Current warning check error: {}".format(e))
        return False

def get_adc_status():
    """获取ADC状态"""
    return {
        "di1_initialized": _di1 is not None,
        "di2_initialized": _di2 is not None,
        "power_pin_available": _power_pin is not None,
        "power_status": _power_status,
        "last_read_time": _last_read_time,
        "adc_data": _adc_data.copy() if _adc_data else None
    }

def collect_adc_data():
    """采集ADC数据"""
    try:
        data = {}
        
        # 读取ADC数据
        adc_data = read_adc()
        if adc_data:
            data.update(adc_data)
        
        # 读取电源状态
        power_status = read_power_status()
        data["power_status"] = power_status
        
        # 获取电源电压
        power_voltage = get_power_voltage()
        data["power_voltage"] = power_voltage
        
        # 检查告警
        data["power_warning"] = check_power_warning()
        data["current_warning"] = check_current_warning()
        
        return data
        
    except Exception as e:
        print("[ADC] Collect ADC data error: {}".format(e))
        return None

def test_adc():
    """测试ADC功能"""
    print("[ADC] Testing ADC functionality...")
    
    # 测试ADC读取
    adc_data = read_adc()
    if adc_data:
        print("[ADC] ADC read test passed: {}".format(adc_data))
    else:
        print("[ADC] ADC read test failed")
    
    # 测试电源状态
    power_status = read_power_status()
    print("[ADC] Power status: {}".format(power_status))
    
    # 测试电源电压
    power_voltage = get_power_voltage()
    print("[ADC] Power voltage: {}V".format(power_voltage))
    
    # 测试告警检查
    power_warning = check_power_warning()
    current_warning = check_current_warning()
    print("[ADC] Power warning: {}, Current warning: {}".format(power_warning, current_warning))
    
    # 测试数据采集
    collected_data = collect_adc_data()
    print("[ADC] Collected data: {}".format(collected_data))
    
    # 显示ADC状态
    status = get_adc_status()
    print("[ADC] ADC status: {}".format(status))
    
    print("[ADC] ADC test completed")